package parsers;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

import weka.core.Instances;
import weka.core.converters.ConverterUtils.DataSource;

/**
 * Simple I/O operations on Weka's .arff files.
 */
public class ArffFileIO {

	/**
	 * Reads an .arrf file and return the instances in it.
	 * 
	 * @param fileName
	 *            Path of the .arff file.
	 * @return Instances inside the file. Last attribute is labelled as the
	 *         class.
	 */
	public static Instances read(String fileName) {
		Instances instances = null;
		try {
			DataSource data = new DataSource(fileName);

			instances = data.getDataSet();

			if (instances.classIndex() == -1) {
				instances.setClassIndex(instances.numAttributes() - 1);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return instances;
	}

	/**
	 * Write the instances to a file in the .arff format.
	 * 
	 * @param instances
	 *            Instances that are written to file
	 * @param fileName
	 *            Path of the file.
	 */
	public static void write(Instances instances, String fileName) {
		try {
			BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
			writer.write(instances.toString());
			writer.newLine();
			writer.flush();
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}
